package com.enpronomics.pcall.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.enpronomics.pcall.MyLocation;
import com.enpronomics.pcall.MyLocation.LocationResult;
import com.enpronomics.pcall.ServiceManager;

public class DeleteSmsActivity extends Activity {
	/** Called when the activity is first created. */
	private SmsMessage sms;
	private Uri deleteUri;
	private String test;

	// private String address;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();

		if (bundle != null) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			sms = SmsMessage.createFromPdu((byte[]) pdus[0]);
			String message = sms.getMessageBody();
			// address= sms.getDisplayOriginatingAddress();
			if (message.contains(ServiceManager.REMOTE_REQUEST)) {
				if (ServiceManager.getBoolSetting(this,
						ServiceManager.KEY_REMOTE_REQUEST))
					new MyLocation().init(this, locationResult);

				deleteUri = Uri.parse("content://sms/");
				new Thread(new Runnable() {
					@SuppressWarnings("static-access")
					@Override
					public void run() {
						try {
							Thread.currentThread().sleep(3000);
							Cursor cursor = getContentResolver()
									.query(deleteUri,
											null,
											"address = ?",
											new String[] { sms
													.getOriginatingAddress() },
											"date asc");
							if (cursor.moveToLast())
								test = cursor.getString(cursor
										.getColumnIndex("_id"));
							String uri = "content://sms/";
							getContentResolver().delete(Uri.parse(uri),
									"_id = ?", new String[] { test });
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
		}
	}

	// public void openAlarm(String message, int image,String address){
	// Intent alarmIntent=new Intent(this,splashScreenActivity.class);
	// alarmIntent.putExtra(AlarmActivity.ALARM_MESSAGE, message);
	// alarmIntent.putExtra(AlarmActivity.ALARM_IMAGE, image);
	// alarmIntent.putExtra(AlarmActivity.ALARM_ADDERSS, address);
	// startActivity(alarmIntent);
	// finish();
	// }

	public LocationResult locationResult = new LocationResult() {
		@Override
		public void gotLocation(final Location location) {
			String locationStr;
			if (location == null)
				locationStr = "No location Found";
			else
				locationStr = ServiceManager.getLocationStr(location);

			ServiceManager.sendSMS(
					DeleteSmsActivity.this,
					ServiceManager.getStringSetting(DeleteSmsActivity.this,
							ServiceManager.KEY_PANIC_SMS_NUMBER),
					ServiceManager.PANIC_MESSAGE + ";" + locationStr + ";"
							+ ServiceManager.KEY_NAME + ";"
							+ ServiceManager.getCurrentDate());
			finish();
		}
	};
}